<template>
  <div class="home-page">
    <el-container direction="vertical" style="align-items: center">
      <el-header height="60px">
        <div class="top-bar">
          <div class="top-container">
            <div class="title-part">
              <p id="title-word">{{ title }}</p>
            </div>
            <div class="user-status">
              <span>Hello {{ userInfo.name }} ! </span>
              <el-link
                @click="loginOut"
                type="primary"
                style="margin-left: 10px"
              >
                Logout</el-link
              >
            </div>
          </div>
        </div>
      </el-header>
      <el-container class="page-container">
        <el-aside>
          <el-card class="user-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>Student Information</span>
              </div>
            </template>

            <div class="text item">
              <div class="info-item">
                <div>Name:</div>
                <div>{{ userInfo.name }}</div>
              </div>
            </div>

            <div class="text item">
              <div class="info-item">
                <div>ID:</div>
                <div>{{ userInfo.student_id }}</div>
              </div>
            </div>

            <div class="text item">
              <div class="info-item">
                <div>Mail:</div>
                <div>{{ userInfo.mail }}</div>
              </div>
            </div>

            <div class="text item">
              <div class="info-item">
                <div>Gender:</div>
                <div>{{ userInfo.gender === 1 ? "Male" : "Female" }}</div>
              </div>
            </div>

            <div class="item">
              <div>
                <el-button
                  type="default"
                  @click="dialogVisible = true"
                  style="margin-bottom: 10px; width: auto"
                >
                  Update Profile
                </el-button>
              </div>
            </div>

            <div class="text item">
              <div class="info-item">
                <div>Certify Code:</div>
                <div>{{ userInfo.certify_code }}</div>
              </div>
              <el-button
                @click="updateCertifyCode"
                style="margin-bottom: 10px; width: auto"
                >{{
                  userInfo.certify_code === ""
                    ? "Generate Certify Code"
                    : "Update Certify Code"
                }}</el-button
              >
            </div>
          </el-card>
        </el-aside>
        <el-main>
          <el-card class="box-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>Dorm Status</span>

                <el-button @click="fetchBuildingsStatus" class="button" circle
                  ><el-icon><refresh /></el-icon
                ></el-button>
              </div>
            </template>
            <el-table :data="buildingsStatus" style="width: 100%">
              <el-table-column prop="building_name" label="Buildings" />
              <el-table-column
                prop="female_available"
                label="Female Remain / Total"
              >
                <template #default="scope">
                  <el-icon><timer /></el-icon>
                  <span
                    style="
                      margin-left: 10px;
                      width: 100px;
                      justify-content: center;
                      display: inline-flex;
                    "
                    >{{ scope.row.female_available }}/{{
                      scope.row.female_total
                    }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column
                prop="male_available"
                label="Male Remain / Total"
              >
                <template #default="scope">
                  <el-icon><timer /></el-icon>
                  <span
                    style="
                      margin-left: 10px;
                      width: 100px;
                      justify-content: center;
                      display: inline-flex;
                    "
                    >{{ scope.row.male_available }}/{{
                      scope.row.male_total
                    }}</span
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
          <div v-if="userDormInfo.roomId === undefined">
            <div class="no-dorm-tips">
              <p>
                Didn't find your room information, please select your room or
                &nbsp;
              </p>
              <el-link @click="getUser2RoomInfo" type="primary">
                Refresh</el-link
              >
            </div>
            <div class="selection-container">
              <el-form
                ref="selectionForm"
                :model="selectionForm"
                :rules="rules"
                label-width="300px"
                label-position="left"
                @keyup.enter="submitForm"
              >
                <el-form-item
                  label="Building"
                  :prop="buildingId"
                  class="form-item"
                >
                  <div class="el-form-item-container">
                    <el-select
                      v-model="selectionForm.buildingId"
                      placeholder="Select Building"
                    >
                      <el-option
                        v-for="item in buildingsStatus"
                        :key="item.building_id"
                        :label="item.building_name"
                        :value="item.building_id"
                      >
                        <span>{{ item.building_name }}</span>
                      </el-option>
                    </el-select>
                  </div>
                </el-form-item>

                <el-form-item label="Nums" :prop="usersNum" class="form-item">
                  <div class="el-form-item-container">
                    <el-input-number
                      v-model="selectionForm.usersNum"
                      :min="1"
                      :max="4"
                      @change="handleNumChange"
                    />
                  </div>
                </el-form-item>

                <div
                  v-for="(user, index) in selectionForm.users"
                  :key="user.userId"
                >
                  <el-form-item
                    :label="'Student ID ' + index"
                    :prop="user.userStudentId"
                    class="form-item"
                  >
                    <div class="el-form-item-container">
                      <el-input
                        :disabled="index === 0"
                        v-model="user.userStudentId"
                      ></el-input>
                    </div>
                  </el-form-item>
                  <el-form-item
                    :label="'Student Certify Code ' + index"
                    :prop="user.userCertifyCode"
                    class="form-item"
                  >
                    <div class="el-form-item-container">
                      <el-input
                        :disabled="index === 0"
                        v-model="user.userCertifyCode"
                      ></el-input>
                    </div>
                  </el-form-item>
                </div>
              </el-form>
            </div>
            <div class="form-butons">
              <!-- <el-button type="primary" style="width: 46%" @click="resetFields"
                >前往注册</el-button
              > -->
              <el-button type="primary" style="width: 30%" @click="submitForm"
                >Submit</el-button
              >
            </div>
          </div>
          <div v-else style="display: block">
            <p class="no-dorm-tips" style="width: 100%">
              Your room number is {{ userDormInfo.roomName }}
            </p>
            <el-button type="primary" style="width: 30%" @click="checkOutRoom">
              Check out</el-button
            >
          </div>
        </el-main>
      </el-container>
    </el-container>

    <el-dialog v-model="dialogVisible" title="Update Profile" width="30%">
      <el-form :model="userInfo">
        <el-form-item label="Student ID" :label-width="formLabelWidth">
          <el-input v-model="userInfo.student_id"></el-input>
        </el-form-item>

        <el-form-item label="Name" :label-width="formLabelWidth">
          <el-input v-model="userInfo.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="Email" :label-width="formLabelWidth">
          <el-input v-model="userInfo.mail" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="Gender" :label-width="formLabelWidth">
          <el-select v-model="userInfo.gender" placeholder="Select your gender">
            <el-option label="Male" :value="1"></el-option>
            <el-option label="Female" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="updateUserProfile"
            >Confirm</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { useRouter } from "vue-router";
import { store } from "@/store";
import { updateCertifyCode, postUpdateUserProfile } from "@/api/user";
import { buildingsStatus, user2RoomInfo, postCheckOutRoom } from "@/api/dorm";
import { postBookOrder } from "@/api/order";
import { mapActions } from "vuex";
import { ref } from "vue";
import { Refresh } from "@element-plus/icons";

export default {
  components: {
    Refresh,
  },

  data: function () {
    return {
      title: "Home",
      userInfo: {
        id: 1,
        name: "John",
        certify_code: "12345678",
      },
      dialogVisible: false,
      formLabelWidth: "100px",
      buildingsStatus: [
        {
          id: 1,
          building_name: "Building 1",
          female_available: 1,
          female_total: 10,
          male_available: 10,
          male_total: 20,
        },
      ],
      userDormInfo: {},
      selectionForm: {
        buildingId: "",
        users: [
          {
            userId: ref(""),
            userStudentId: ref(""),
            userCertifyCode: ref(""),
          },
        ],
        usersNum: 1,
      },
      rules: {},
    };
  },
  methods: {
    ...mapActions("user", ["LoginOut"]),
    async loginOut() {
      this.toLogin();
      return await this.LoginOut();
    },
    updateCertifyCode: function () {
      const that = this;
      updateCertifyCode().then((res) => {
        that.userInfo.certify_code = res.data.certifyCode;
        that.selectionForm.users[0].userCertifyCode = res.data.certifyCode;
      });
    },

    fetchBuildingsStatus: function () {
      const that = this;
      buildingsStatus().then((res) => {
        that.buildingsStatus = res.data;
      });
    },

    getUser2RoomInfo: function () {
      const that = this;
      user2RoomInfo().then((res) => {
        console.log(res);
        that.userDormInfo = res.data.userDormInfo;
      });
    },

    handleNumChange: function (val) {
      // this.selectionForm.users = [];
      let diff = val - this.selectionForm.users.length;
      console.log(diff);
      if (diff > 0) {
        for (let i = 0; i < diff; i++) {
          this.selectionForm.users.push({
            userId: ref(""),
            userStudentId: ref(""),
            userCertifyCode: ref(""),
          });
        }
      } else {
        for (let i = 0; i < -diff; i++) {
          this.selectionForm.users.pop();
        }
      }
    },

    submitForm: function () {
      this.$refs.selectionForm.validate(async (valid) => {
        if (valid) {
          let code = await this.bookOrder();
          if (code != 200) {
            this.$message.error("请选择宿舍");
          } else {
            this.$message.success("提交成功，请刷新页面");
          }
        }
      });
    },

    bookOrder: async function () {
      const that = this;
      const { buildingId, users, usersNum } = this.selectionForm;
      const payload = {
        buildingId,
        users,
        usersNum,
        gender: that.userInfo.gender,
      };
      let returnCode;

      await postBookOrder(payload).then((res) => {
        if (res.code == 200) console.log(res);
        returnCode = res.code;
      });
      return returnCode;
    },

    updateUserProfile: async function () {
      const that = this;
      const payload = {
        student_id: that.userInfo.student_id,
        name: that.userInfo.name,
        mail: that.userInfo.mail,
        gender: that.userInfo.gender,
      };

      await postUpdateUserProfile(payload).then((res) => {
        console.log(res);
        if (res.code == 200) {
          that.$message.success("信息修改成功，请重新登录");
          that.toLogin();
        } else {
          this.$message.success("修改失败，请刷新重试");
        }
      });
      this.dialogVisible = false;
    },

    checkOutRoom: async function () {
      const that = this;
      const payload = {
        userId: String(that.userInfo.id),
        roomId: String(that.userDormInfo.roomId),
      };
      await postCheckOutRoom(payload).then((res) => {
        console.log(res);
        if (res.code == 200) {
          that.$message.success("退宿成功");
          that.userDormInfo = {};
        } else {
          that.$message.error("退宿失败，请刷新重试");
        }
      });
    },
  },
  setup() {
    // const route = useRoute();
    const router = useRouter();
    const toLogin = () => {
      router.push("/login");
    };
    return {
      toLogin: toLogin,
    };
  },
  mounted() {
    // store.dispatch("getUserInfo");
    this.userInfo = store.getters["user/userInfo"];
    this.fetchBuildingsStatus();
    this.getUser2RoomInfo();
    this.selectionForm.users[0].userId = this.userInfo.id;
    this.selectionForm.users[0].userStudentId = this.userInfo.student_id;
    this.selectionForm.users[0].userCertifyCode = this.userInfo.certify_code;
    if (this.userInfo.id === "") {
      this.$message.error("请先登录");
      this.toLogin();
    }
  },
};
</script>
<style  scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.user-card {
  border-radius: 5px;
}

.no-dorm-tips {
  display: inline-flex; /* 在线编辑器中，不能使用inline-block */
  line-height: 30px;
  height: 30px;
  margin-bottom: 30px;
  justify-content: center;
}

.home-page {
  /* display: flex; */

  background-image: url("../../assets/login_background.svg");
  background-size: cover;

  display: block;
  width: 100%;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100%;
  overflow: visible !important;
}

.top-bar {
  height: 60px;
  width: 100%;

  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.top-container {
  display: flex;
  height: 100%;
  justify-content: space-between;
  margin: 0 auto;
  margin-top: 0px;
  margin-right: auto;
  margin-bottom: 0px;
  margin-left: auto;
}

.title-part {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-left: 20%;
}

.user-status {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20%;
}

.el-header,
.el-footer {
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 60px;
  width: 100%;
  padding: 0;

  background-color: rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(5px);
}

.el-aside {
  padding: 20px;
  /* background: #d3dce6 60%; */
  color: var(--el-text-color-primary);
  text-align: center;
  justify-content: center;

  background-color: rgba(255, 255, 255, 0);
  backdrop-filter: blur(0px);
}

.el-main {
  background-color: #e9eef3;
  color: var(--el-text-color-primary);
  text-align: center;

  background-color: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(5px);
}

.page-container {
  width: 1200px;
}

.info-item {
  justify-content: space-between;
  display: flex;
  margin: 10px 20px 10px 20px;
}

.el-input {
  width: 200px;
}

.selection-container {
  margin: 10px 100px 10px 100px;
}

.el-form-item-container {
  text-align: end;
}
</style>
